package com.hsogoo.study.leetcode.addtwonums;

/**
 * 两数相加
 * 解法：指针遍历进位
 */
class Solution {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1 == null){
            return l2;
        }
        if(l2 == null){
            return l1;
        }
        ListNode head = new ListNode(0);
        ListNode c1 = l1;
        ListNode c2 = l2;
        int add = 0;
        ListNode current = head;
        while(c1 != null || c2 != null){
            int val1 = (c1 == null)?0:c1.val;
            int val2 = (c2 == null)?0:c2.val;
            int sum = val1 + val2 + add;
            add = sum/10;
            current.next = new ListNode(sum % 10);
            current = current.next;
            if(c1 != null){
                c1 = c1.next;
            }
            if(c2 != null){
                c2 = c2.next;
            }
        }
        //last node add
        if(add > 0){
            current.next = new ListNode(add);
        }
        
        return head.next;
        
    }

    public static class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }

    public static void main(String[] args) {
        //输入：(2 -> 4 -> 3) + (5 -> 6 -> 4)
        //输出：7 -> 0 -> 8
        //原因：342 + 465 = 807

        ListNode node11 = new ListNode(2);
        ListNode node12 = new ListNode(4);
        ListNode node13 = new ListNode(3);
        node11.next = node12;
        node12.next = node13;

        ListNode node21 = new ListNode(5);
        ListNode node22 = new ListNode(6);
        ListNode node23 = new ListNode(4);
        node21.next = node22;
        node22.next = node23;

        Solution s = new Solution();
        ListNode result = s.addTwoNumbers(node11, node21);
        ListNode current = result;
        while(current != null){
            System.out.print(current.val);
            if(current.next != null){
                System.out.print("->");
            }
            current = current.next;
        }
    }
}